package com.ruoyi.project.system.service.impl;

import com.ruoyi.project.system.domain.Question;
import com.ruoyi.project.system.domain.QuestionAnswer;
import com.ruoyi.project.system.mapper.QuestionMapper;
import com.ruoyi.project.system.mapper.QuestionAnswerMapper;
import com.ruoyi.project.system.service.IQuestionnaireService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问卷服务实现
 */
@Service
public class QuestionnaireServiceImpl implements IQuestionnaireService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionAnswerMapper answerMapper;

    @Override
    public List<Map<String, Object>> getQuestionnaireByDept(String department) {
        List<Map<String, Object>> questionnaire = new ArrayList<>();

        // 1. 根据科室名查问题（按sort排序）
        List<Question> questionList = questionMapper.selectQuestionByDept(department);
        if (CollectionUtils.isEmpty(questionList)) {
            return questionnaire; // 无问题返回空列表
        }

        // 2. 为每个问题匹配对应的选项（按sort排序）
        for (Question question : questionList) {
            Map<String, Object> questionMap = new HashMap<>();
            questionMap.put("text", question.getQuestion()); // 问题文本

            // 查当前问题的所有选项
            List<QuestionAnswer> answerList = answerMapper.selectAnswerByQuestionId(question.getId());
            List<String> options = new ArrayList<>();
            for (QuestionAnswer answer : answerList) {
                options.add(answer.getAnswer()); // 收集选项文本
            }
            questionMap.put("options", options); // 选项列表

            questionnaire.add(questionMap);
        }

        return questionnaire;
    }
}